# -*- coding: utf-8 -*-

# ChannelInfo
# Feel free to add comments and pas extra stuff You would have fitted in.
# gravatasufoca@yahoo.com.br
# Bruno Teixeira canto de Lima 

from Components.ActionMap import ActionMap

from Components.NimManager import nimmanager
from Components.config import *
from Components.ConfigList import ConfigList, ConfigListScreen
from Plugins.Plugin import PluginDescriptor
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Components.Sources.StaticText import StaticText

twinchannel_version = "1.0"
twinchannel_plugindir = "/usr/lib/enigma2/python/Plugins/Extensions/TwinChannel" 
twinchannel_title = "TwinChannel"
twinchannel_developer = "GravataSufoca"

# Configuration
# Channel
config.plugins.TwinChannel = ConfigSubsection()
config.plugins.TwinChannel.tipo = ConfigSelection(default="oscam", choices=[
        ("twin", "twin"),
        ("oscam", "oscam")
        ])

config.plugins.TwinChannel.pasta=ConfigDirectory(default="/tmp/oscam.twin",visible_width = 500 )
config.plugins.TwinChannel.radio=ConfigYesNo()

# Class TwinChannelScreen
class TwinChannelScreen(ConfigListScreen, Screen):

    def __init__(self, session):
        self.session = session
        Screen.__init__(self, session)
        self.skinName = [ "Setup" ]
        self.list = []
        self["config"] = ConfigList(self.list)

        self.onChangedEntry=[]
        
        self.satConfigureds = nimmanager.getConfiguredSats()
       
        self.sats={}
        for sat in self.satConfigureds:
            self.sats[sat]= ConfigYesNo(default=True)  
            caid="%s_caid"%sat
            self.sats[caid]=ConfigText(default="1802",fixed_size=False)  
            
            
        
        ConfigListScreen.__init__(self, self.list, session=self.session,on_change=self.changePath)
         
        self["key_red"] = StaticText(_("Cancel"))
        self["key_green"] = StaticText(_("Create"))        
        
        
        self["actions"] = ActionMap(["InputActions","ColorActions", "setupActions"],
        {
            "green": self.confirma,
            "red": self.cancel,
            "cancel": self.cancel
        }, -2)
        
        self.changedEntry()
    
    def changePath(self):
        for x in self.onChangedEntry:
            x()
            
        if config.plugins.TwinChannel.tipo.value=="oscam":
            config.plugins.TwinChannel.pasta.text="/tmp/oscam.twin"
        elif config.plugins.TwinChannel.tipo.value=="twin":
            config.plugins.TwinChannel.pasta.text= "/tmp/twin2cc.channelinfo"
        

    def changedEntry(self):
        
        for x in self.onChangedEntry:
            x()

        self.list=[]
        self.list.append(getConfigListEntry("Type", config.plugins.TwinChannel.tipo))
        self.list.append(getConfigListEntry("Path", config.plugins.TwinChannel.pasta))
        self.list.append(getConfigListEntry("Radio", config.plugins.TwinChannel.radio))

        
        
        for key,value in self.sats.items():
            if not str(key).endswith("_caid"):   
                satName=nimmanager.getSatName(int(key))[:1][0]
                self.list.append(getConfigListEntry(satName, value))            
                if value.value:
                    caid="%s_caid"%key
                    self.list.append(getConfigListEntry("CAID", self.sats[caid]))      

        
        self["config"].list = self.list
        self["config"].setList(self.list)
        
                
    def cancel(self):
        for i in self["config"].list:
            i[1].cancel()
        self.close(False)
        
        
    def confirma(self):
        self.changedEntry()
        if config.plugins.TwinChannel.pasta.value=="":
            self.session.open(MessageBox, "Please choose the path!", MessageBox.TYPE_WARNING, close_on_any_key=True, timeout=5)
        else:
            self.session.openWithCallback(self.gerarChannel, MessageBox, _("Do you really want to create the file?"), MessageBox.TYPE_YESNO)

    
    def gerarLinha(self,caid, sid, position, frequencia, nome,satName):
        linha=""
        if config.plugins.TwinChannel.tipo.value=="twin":
            linha= "%s:000000:%s:%s:%s \"%s (%s)\"\n" % (caid, sid, position, frequencia, nome,satName)
        elif config.plugins.TwinChannel.tipo.value=="oscam":
            linha= "%s:000000:%s:%s:%s # %s (%s)\n" % (caid, position, frequencia,sid,nome,satName)
        
        return linha

    def formataPosicao(self,posicao):
        if config.plugins.TwinChannel.tipo.value=="twin":
            position=hex(posicao)[2:]          
      
            position=str(position)
            i = 4-len(position)
            while i > 0:
                position = "0%s" % position
                i -= 1 
            
        elif config.plugins.TwinChannel.tipo.value=="oscam":
            position=posicao
            if posicao % 10 >0:
                position=posicao+1
            
            position=str(position)
        
        return position
    
    def formataSid(self,sid):
        if config.plugins.TwinChannel.tipo.value=="twin":
            ss=str(sid)
            i = 4-len(str(ss))
            while i > 0:
                ss = "0%s" % ss
                i -= 1 
        elif config.plugins.TwinChannel.tipo.value=="oscam":
            ss=str(int(sid,16))
        
        return ss
        
    def formataFrequencia(self,frequencia):
        if config.plugins.TwinChannel.tipo.value=="twin":
            freq = hex(int(frequencia) / 1000)[2:]
        elif config.plugins.TwinChannel.tipo.value=="oscam":
            freq = int(frequencia) / 1000
        
        return freq

    def getArquivoLabel(self):
        if config.plugins.TwinChannel.tipo.value=="twin":
            return "CHANNELINFO"
        elif config.plugins.TwinChannel.tipo.value=="oscam":
            return "OSCAM.TWIN"
        elif config.plugins.TwinChannel.tipo.value=="epg":
            return "EPG"
        
    
    def getTipos(self):
        tipos=["1","19","25"]
        if config.plugins.TwinChannel.radio.value:
            tipos.append("2")
        
        return tipos
            
        
    def gerarChannel(self,answer):
        
        if answer:            
            from enigma import eServiceReference, eServiceCenter, iServiceInformation
            from Components.Sources.ServiceList import ServiceList        
            import re
    
    
            currentServiceRef = self.session.nav.getCurrentlyPlayingServiceReference()
            servicelist = ServiceList("")
            servicelist.setRoot(currentServiceRef)
            canais = servicelist.getServicesAsList()
            
            servicehandler = eServiceCenter.getInstance()
            
            canaisValidos={}
            count=0
            for item in canais:
                canal = eServiceReference(item[0])            
                if canal:   
                    tipo=item[0].split(":")[2]         
                    if tipo in self.getTipos():             
                        transponder_info = servicehandler.info(canal).getInfoObject(canal, iServiceInformation.sTransponderData)
                        
                        if not transponder_info["tuner_type"] in ["DVB-S","DVB-S2"]:
                            continue
                        
                        frequencia = self.formataFrequencia(transponder_info["frequency"])
                        sid = canal.toString().split(":")[3]
                        position = int(transponder_info["orbital_position"])
                        satName= nimmanager.getSatName(position).split(" ")[:1][0]
                        
                        position=self.formataPosicao(position)
                        
                        sid=self.formataSid(sid)
                            
                        nome = servicehandler.info(canal).getName(canal)
                        caid="%s"%self.sats["%s_caid"%transponder_info["orbital_position"]].value                          
                        count+=1
                      
                        canaisValidos[count]=self.gerarLinha( caid, sid, position, frequencia, nome, satName)
                    
            
            tmp = open(config.plugins.TwinChannel.pasta.value, "w")
            tmp.write("################### TWINCHANNEL by GravataSufoca - %s ######################\n"%self.getArquivoLabel())     
            canais=canaisValidos.items()
            
            if config.plugins.TwinChannel.tipo.value=="twin":
                canais.sort(key=lambda x: (re.split("\"",x[1]))[1] )
            elif config.plugins.TwinChannel.tipo.value=="oscam":
                canais.sort(key=lambda x: (re.split(":",x[1]))[2] ,reverse=True)


            for valor in canais:
                tmp.write(valor[1])
            
            tmp.close()
            
            self.session.open(MessageBox,_("The channel list was created successfully!\n%d channels was created.") % (canaisValidos.__len__()), MessageBox.TYPE_WARNING, close_on_any_key=True, timeout=5)
    
    
# Function main
def main(session, **kwargs):
    session.open(TwinChannelScreen)


# Plugin descriptor, name, icon, etc.
def Plugins(**kwargs):
    return [
        PluginDescriptor(where=PluginDescriptor.WHERE_PLUGINMENU, fnc=main, icon="plugin.png", name=twinchannel_title, description="Create the channel list for the twin protocol for Oscam and twins"),
        PluginDescriptor(where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main, icon="plugin.png", name=twinchannel_title, description="Create the channel list for the twin protocol for Oscam and twins")

      ]
